# coding: utf-8
from typing import Callable

from sqlalchemy.orm import Session

from .base import RequestHandler, EventSignalBus, QueueThread

sqlSignalBus = EventSignalBus()


def sqlRequest(func: Callable, *args, slot=None, **kwargs):
    """ 从数据库查询 SQL 数据 """
    request = RequestHandler(func, slot, *args, **kwargs)
    sqlSignalBus.fetchDataSignal.emit(request)


class DatabaseThread(QueueThread):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.server = None
        self.session: Session = None
        sqlSignalBus.fetchDataSignal.connect(self.addTask)
        self.result.connect(sqlSignalBus.resultSignal)

    def setUp(self):
        func, args, kwargs = self.server
        self.session: Session = func(*args, **kwargs)

    def handleTask(self, task: RequestHandler):
        result = task.func(*task.args, **task.kwargs, session=self.session)
        return result

    def tearDown(self):
        self.session.close()

    def setServer(self, func: Callable, *args, **kwargs):
        self.server = (func, args, kwargs)
